<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主题编号" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入主题编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="专业" prop="majorName">
        <el-input
          v-model="queryParams.majorName"
          placeholder="请输入专业"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['request:requirement:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['request:requirement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['request:requirement:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['request:requirement:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 第一种样式风格 -->
    <!-- <el-table v-loading="loading" :data="requirementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="要求编号" align="center" prop="requirementId" />
      <el-table-column label="主题编号" align="center" prop="title" />
      <el-table-column label="内容" align="center" prop="content" />
      <el-table-column label="关联专业" align="center" prop="majorName" />
      <el-table-column label="关联课程" align="center">
      <template v-slot="{ row }">
        <span v-if="row.courseNameList && row.courseNameList.length">
          {{ row.courseNameList.join(', ') }}
        </span>
        <span v-else>无</span>
      </template>
      </el-table-column>
      <el-table-column label="支持系数" align="center">
        <template v-slot="{ row }">
          <span v-if="row.courseRequirementList && row.courseRequirementList.length">
            {{ row.courseRequirementList.map(item => item.coefficient).join(', ') }}
          </span>
          <span v-else>无</span>
        </template>
      </el-table-column> -->

      <!-- 第二种样式风格 -->
      <el-table v-loading="loading" :data="requirementList" @selection-change="handleSelectionChange" border>
          <!-- 展开按钮 -->
        <el-table-column type="expand">
          <template v-slot="{ row }">
            <el-table :data="formatCourseData(row)" border>
              <el-table-column label="关联课程" prop="courseName" align="center" />
              <el-table-column label="支持系数" prop="coefficient" align="center" />
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="要求编号" align="center" prop="requirementId" />
        <el-table-column label="主题编号" align="center" prop="title" />
        <el-table-column label="内容" align="center" prop="content" />
        <el-table-column label="关联专业" align="center" prop="majorName" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['request:requirement:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['request:requirement:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程毕业要求对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="主题编号" prop="title">
          <el-input v-model="form.title" placeholder="请输入主题编号" />
        </el-form-item>
        
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>

        <!-- 选择专业 -->
        <el-form-item label="专业" prop="majorId">
          <el-select v-model="form.majorId" placeholder="请选择专业" clearable>
            <el-option v-for="item in majorList" :key="item.majorId" :label="item.name" :value="item.majorId" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="专业" prop="majorId">
          <el-select v-model="form.majorId" placeholder="请选择专业" clearable>
            <el-option v-for="item in majorList" :key="item.majorId" :label="item.name" :value="item.majorId" />
          </el-select>
        </el-form-item> -->

        <el-divider content-position="center">课程毕业要求信息</el-divider>

        <!-- 课程选择 -->
        <el-form-item label="关联课程">
          <el-select v-model="selectedCourse" placeholder="请选择课程" clearable>
            <el-option v-for="item in courseList" :key="item.courseId" :label="item.courseName" :value="item.courseId" />
          </el-select>
          &nbsp;
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddCourseRequirement">添加</el-button>
        </el-form-item>

        <el-table :data="courseRequirementList" border>
          <el-table-column label="课程名称" prop="courseName" align="center" />
          <el-table-column label="支持系数" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.coefficient" placeholder="请输入支持系数" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-delete" @click="handleDeleteCourseRequirement(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="主题编号" prop="title">
          <el-input v-model="form.title" placeholder="请输入主题编号" />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="专业编号" prop="majorId">
          <el-input v-model="form.majorId" placeholder="请输入专业编号" />
        </el-form-item>
        <el-divider content-position="center">课程毕业要求信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddCourseRequirement">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteCourseRequirement">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="courseRequirementList" :row-class-name="rowCourseRequirementIndex" @selection-change="handleCourseRequirementSelectionChange" ref="courseRequirement">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="课程对毕业要求的支持系数" prop="coefficient" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.coefficient" placeholder="请输入课程对毕业要求的支持系数" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import { listRequirement, getRequirement, delRequirement, addRequirement, updateRequirement, getMajors, getCourses } from "@/api/pingjiao/requirement";

export default {
  name: "Requirement",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedCourseRequirement: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程毕业要求表格数据
      requirementList: [],
      // 课程毕业要求表格数据
      courseRequirementList: [],
      // 专业列表
      majorList: [],
      // 课程列表
      courseList: [],
      // 用户选择的课程
      selectedCourse: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        content: null,
        majorId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getMajorList();
    this.getCourseList();
  },
  methods: {
    //组合 关联课程和关联系数 的数据
    formatCourseData(row) {
      if (!row.courseNameList || !row.courseRequirementList) return [];
      return row.courseNameList.map((courseName, index) => ({
        courseName: courseName,
        coefficient: row.courseRequirementList[index]?.coefficient || '无'
      }));
    },

    /** 查询课程毕业要求列表 */
    getList() {
      this.loading = true;
      listRequirement(this.queryParams).then(response => {
        this.requirementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取所有专业 */
    getMajorList() {
      getMajors().then(response => {
        this.majorList = response.rows;
      })
    },
    
    /** 获取所有课程 */
    getCourseList() {
      getCourses().then(response => {
        this.courseList = response.rows;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        requirementId: null,
        title: null,
        content: null,
        majorId: null
      };
      this.courseRequirementList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.requirementId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程毕业要求";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const requirementId = row.requirementId || this.ids;
      getRequirement(requirementId).then(response => {
        this.form = response.data;
        // 回显专业名称
        this.form.majorId = response.data.majorId;  // 保留专业 ID
        const major = this.majorList.find(item => item.majorId === response.data.majorId);
        this.form.majorName = major ? major.name : ''; // 显示专业名称
        // 回显课程列表
        this.courseRequirementList = response.data.courseRequirementList.map(item => {
          const course = this.courseList.find(c => c.courseId === item.courseId);
          return {
            courseId: item.courseId,
            courseName: course ? course.courseName : '未知课程',
            coefficient: item.coefficient
          };
        });
        this.open = true;
        this.title = "修改课程毕业要求";
      });
    },
    // handleUpdate(row) {
    //   this.reset();
    //   const requirementId = row.requirementId || this.ids
    //   getRequirement(requirementId).then(response => {
    //     this.form = response.data;
    //     this.courseRequirementList = response.data.courseRequirementList;
    //     this.open = true;
    //     this.title = "修改课程毕业要求";
    //   });
    // },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.courseRequirementList = this.courseRequirementList.map(item => ({
            courseId: item.courseId,
            coefficient: item.coefficient
          }));
          if (this.form.requirementId != null) {
            updateRequirement(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRequirement(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // submitForm() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       this.form.courseRequirementList = this.courseRequirementList;
    //       if (this.form.requirementId != null) {
    //         updateRequirement(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addRequirement(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const requirementIds = row.requirementId || this.ids;
      this.$modal.confirm('是否确认删除课程毕业要求编号为"' + requirementIds + '"的数据项？').then(function() {
        return delRequirement(requirementIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	  /** 课程毕业要求序号 */
    rowCourseRequirementIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 添加选中的课程 */
    handleAddCourseRequirement() {
      if (!this.selectedCourse) {
        this.$message.error("请选择课程");
        return;
      }
      const selectedCourseObj = this.courseList.find(item => item.courseId === this.selectedCourse);
      if (this.courseRequirementList.some(item => item.courseId === this.selectedCourse)) {
        this.$message.error("该课程已添加");
        return;
      }
      this.courseRequirementList.push({
        courseId: selectedCourseObj.courseId, // 存 ID
        courseName: selectedCourseObj.courseName, // 显示名称
        coefficient: ""
      });

      this.selectedCourse = null; // 清空选择框
    },
    /** 删除某个课程 */
    handleDeleteCourseRequirement(row) {
      this.courseRequirementList = this.courseRequirementList.filter(item => item.courseId !== row.courseId);
    },
    /** 复选框选中数据 */
    handleCourseRequirementSelectionChange(selection) {
      this.checkedCourseRequirement = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('request/requirement/export', {
        ...this.queryParams
      }, `requirement_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>




